package util

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/sirupsen/logrus"
	"path/filepath"
	"runtime"
	"strings"
)

type CustomFormatter struct {
	logrus.TextFormatter
	UseColor bool
}

func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format(f.TimestampFormat)
	level := strings.ToUpper(entry.Level.String())
	msg := entry.Message

	// 获取当前的文件和行号信息
	_, file, line, _ := runtime.Caller(4)
	file = filepath.Base(file)

	// 获取当前函数名
	//pc, _, _, _ := runtime.Caller(3)
	//funcName := runtime.FuncForPC(pc).Name()
	//funcName = filepath.Ext(funcName) + "(" + funcName + ")"
	if f.UseColor {
		// 构建格式化后的日志行
		levelColorized := f.getColorizedLevel(level)
		timestampColorized := f.getColorizedTimestamp(timestamp)
		fileColorized := f.getColorizedFile(file)
		msgColorized := f.getColorizedMsg(msg)

		lineStr := fmt.Sprintf("%s-[%s]-%s:%d ==> %s\n", timestampColorized, levelColorized, fileColorized, line, msgColorized)
		fmt.Println("1111")
		return []byte(lineStr), nil
	} else {
		lineStr := fmt.Sprintf("%s-[%s]-%s:%d ==> %s\n", timestamp, level, file, line, msg)
		fmt.Println("2222")
		return []byte(lineStr), nil
	}

}

func (f *CustomFormatter) getColorizedLevel(level string) string {
	switch level {
	case "DEBUG":
		return color.New(color.FgCyan).SprintFunc()(level)
	case "INFO":
		return color.New(color.FgGreen).SprintFunc()(level)
	case "WARN", "WARNING":
		return color.New(color.FgYellow).SprintFunc()(level)
	case "ERROR":
		return color.New(color.FgRed).SprintFunc()(level)
	case "FATAL", "PANIC":
		return color.New(color.BgRed, color.FgWhite).SprintFunc()(level)
	default:
		return level
	}
}

func (f *CustomFormatter) getColorizedTimestamp(timestamp string) string {
	return color.New(color.FgHiBlack).SprintFunc()(timestamp)
}

func (f *CustomFormatter) getColorizedFile(file string) string {
	return color.New(color.FgBlue).SprintFunc()(file)
}

func (f *CustomFormatter) getColorizedMsg(msg string) string {
	return color.New(color.FgWhite).SprintFunc()(msg)
}
